﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Koonsoft.HYCRM.DAL
{
    public class HttpHelper
    {
        public static CookieContainer Cookie = new CookieContainer();
        public static Encoding StringEncoding;
        
        public string GetParameter(Dictionary<string, string> dic)
        {
            if (dic == null)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair<string, string> pair in dic)
            {
                sb.AppendFormat("{0}={1}&", pair.Key, pair.Value);
            }

            return sb.ToString().TrimEnd('&');
        }

        public HttpHelper()
        {
            StringEncoding = Encoding.UTF8;
        }

        public void Channel(Uri domain,string key,string newValue )
        {
             foreach (Cookie cookie in Cookie.GetCookies(domain))
            {
                if (cookie.Name.ToLower() == key.ToLower())
                {
                    cookie.Value = newValue;
                }
            }
        }

        public void Channel(string domain, Dictionary<string, string> cookies,string path = "/")
        {
            CookieCollection _cookies = Cookie.GetCookies(new Uri(domain));
            foreach (var v in cookies)
            {
                if (_cookies[v.Key] !=null)
                {
                    _cookies[v.Key].Value = v.Value;
                }
                else
                {
                    if (string.IsNullOrEmpty(path)|| path.Trim()=="/")
                    {
                        Cookie.Add(new Uri(domain), new Cookie(v.Key, v.Value));
                    }
                    else
                    {
                        Cookie.Add(new Uri(domain), new Cookie(v.Key, v.Value, string.Format("/{0}/", path.Trim('/'))));
                    }
                    _cookies = Cookie.GetCookies(new Uri(domain));
                }
            }
        }

        public HttpWebResponse GetHttpWebResponse(string url, Dictionary<string, string> parameter)
        {
            if (parameter != null && parameter.Count > 0)
            {
                url = url + "?" + GetParameter(parameter);
            }


            var req = (HttpWebRequest)WebRequest.Create(new Uri(url));
            req.CookieContainer = Cookie;

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            if (res.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("网络连接错误");
            }

            return res;
        }

        public string Get(string url, Dictionary<string, string> parameter = null)
        {
            var res = GetHttpWebResponse(url, parameter);

            var sr = new StreamReader(res.GetResponseStream(), StringEncoding);
            var str = sr.ReadToEnd();
            sr.Close();
            res.Close();

            return str;
        }

        public HttpWebResponse PostHttpWebResponse(string url, Dictionary<string, string> parameter)
        {
            string postData = "";
            if (parameter != null && parameter.Count > 0)
            {
                postData = GetParameter(parameter);
            }

            var req = (HttpWebRequest)WebRequest.Create(new Uri(url));
            req.CookieContainer = Cookie;

            byte[] data = Encoding.UTF8.GetBytes(postData);


            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";


            var newStream = req.GetRequestStream();

            // Send the data.  
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            var res = (HttpWebResponse)req.GetResponse();

            if (res.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("网络连接错误");
            }


            return res;
        }

        public string Post(string url, Dictionary<string, string> parameter = null)
        {
            var res = GetHttpWebResponse(url, parameter);

            var sr = new StreamReader(res.GetResponseStream(), StringEncoding);
            var str = sr.ReadToEnd();
            sr.Close();
            res.Close();

            return str;
        }

    }
}
